package com.xdxc.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xdxc.model.bo.UserAnswerWithGrading;
import com.xdxc.model.entity.TempUserAnswer;
import com.xdxc.model.vo.UserAnswerVo;
import com.xdxc.utils.JsonTypeHandler;

import org.apache.ibatis.annotations.*;

import java.math.BigDecimal;
import java.util.List;

@Mapper
public interface TempUserAnswerMapper extends BaseMapper<TempUserAnswer> {
    @Options(useGeneratedKeys = false, flushCache = Options.FlushCachePolicy.TRUE)
    @Update("<script>" +
            "INSERT INTO temp_user_answer " +
            "(id, paper_id, qu_id, answer_type, answer_ids, answer_text, version, user_id,exam_id,check_id) " +
            "VALUES " +
            "<foreach collection='list' item='item' separator=','>" +
            "(#{item.id}, #{item.paperId}, #{item.quId}, #{item.answerType}, " +
            "#{item.answerIds, typeHandler=com.xdxc.utils.JsonTypeHandler}, " +
            "#{item.answerText}, " +
            "#{item.version}, #{item.userId}, #{item.examId}, #{item.checkId})" +
            "</foreach>" +
            "ON DUPLICATE KEY UPDATE " +
            "answer_ids = VALUES(answer_ids), " +
            "answer_text = VALUES(answer_text), " +
            "version = version + 1, " +
            "update_time = NOW()" +
            "</script>")
    int batchUpsert(@Param("list") List<TempUserAnswer> list);

    // 新增：按主键排序的批量更新（防止死锁）
    @Update("<script>" +
            "INSERT INTO temp_user_answer " +
            "(id, paper_id, qu_id, answer_type, answer_ids, answer_text, answer_files, version, is_deleted, update_time, answer_type_text, user_id) " +
            "VALUES " +
            "<foreach collection='list' item='entity' separator=','>" +
            "(#{entity.id}, #{entity.paperId}, #{entity.quId}, #{entity.answerType}, " +
            "#{entity.answerIds, typeHandler=com.xdxc.utils.JsonTypeHandler}, " +
            "#{entity.answerText}, " +
            "#{entity.answerFiles, typeHandler=com.xdxc.utils.JsonTypeHandler}, " +
            "#{entity.version}, #{entity.isDeleted}, " +
            "NOW(), #{entity.answerTypeText}, #{entity.userId})" +
            "</foreach>" +
            "ON DUPLICATE KEY UPDATE " +
            "answer_ids = VALUES(answer_ids), " +
            "answer_text = VALUES(answer_text), " +
            "answer_files = VALUES(answer_files), " +
            "version = VALUES(version) + 1, " +
            "is_deleted = VALUES(is_deleted), " +
            "update_time = NOW(), " +
            "answer_type_text = VALUES(answer_type_text), " +
            "user_id = VALUES(user_id)" +
            "</script>")
    void batchUpsertOrdered(@Param("list") List<TempUserAnswer> entities);



    List<UserAnswerVo> selectByPaperIdWithGrading(@Param("paperId") Long paperId);
}
